// pages/insurance/insurance.js
var utils = require('../../utils/utils.js');
let hyMath = require('../../utils/math.js');

var storage = require('../../utils/storage.js')
var request = require('../../utils/request.js')
var auth = require('../../utils/auth.js');
var config = require('../../config.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        insuranceCompanyList: [
            // {
            // name:'请选择',
            // value:'0'
            // }
        ],
        insuranceCompanyListIndex: 0,
        urlP: {
            items: undefined
        },
        userInfo: {
            real_name: '',
            head_img_url: '',
            default_img_url: '../../images/ic-touxiang-moren.png',
        },
        submitEx: {
            "member_id": "", // 会员id（新、旧会员id，两者只能有一个存在）
            "old_member_id": "", // 旧会员id（新、旧会员id，两者只能有一个存在）
            "car_plate": "", // 车牌号
        },
        submitP: {
            company_type: '1',
            original_amount: '',
            proportion: '30',
            amount: '',
        },
        hasLogin: true,
        right: '../../images/right.png',
        disabled: false
    },
    bindPickerChange(e) {
        // console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            insuranceCompanyListIndex: e.detail.value
        })
        this.setData({
            'submitP.company_type': e.detail.value - 0 + 1
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this;
        let insuranceCompanyList = that.data.insuranceCompanyList;
        request.post({'path': config.insuranceCompanyList}, {}).then(function (res) {
            var data = res.data;
            if (data.ret == 0) {
                insuranceCompanyList.push(...data.data);

                that.setData({
                    insuranceCompanyList: insuranceCompanyList
                })
            }
        })
    },
    //选择保险公司

    // 确认提交
    confirmFn() {
        let that = this;
        wx.showModal({
            title: '提示',
            content: '提交后，该数据将进入保险日报统计',
            success: function (res) {
                if (res.confirm) {
                    that.sureFn();
                } else {
                    console.log('用户点击取消')
                }

            }
        })
    },
    sureFn() {
        var that = this;
        let ex = that.data.submitEx;
        let submitP = that.data.submitP;
        if (!that.data.disabled) {
            that.setData({
                disabled: true
            })

            // "member_id": "", // 会员id（新、旧会员id，两者只能有一个存在）
            //     "old_member_id": ""


            if (!that.data.submitEx.member_id && !that.data.submitEx.old_member_id) {
                wx.showToast({
                    icon: 'none',
                    title: '请选择用户'
                })
                that.setData({
                    disabled: false
                });
                return false;
            }

            if (!that.data.submitP.company_type) {
                wx.showToast({
                    icon: 'none',
                    title: '请输入保险公司'
                })
                that.setData({
                    disabled: false
                });
                return false;
            }

            if (!that.data.submitP.company_type) {
                wx.showToast({
                    icon: 'none',
                    title: '请输入保险公司'
                })
                that.setData({
                    disabled: false
                });
                return false;
            } else if (!that.data.submitP.original_amount) {
                wx.showToast({
                    icon: 'none',
                    title: '请输入商业险金额'
                })
                that.setData({
                    disabled: false
                });
                return false;
            } else if (!that.data.submitP.amount) {
                wx.showToast({
                    icon: 'none',
                    title: '请输入实收金额'
                })
                that.setData({
                    disabled: false
                });
                return false;
            }
            //新对象
            let data = {};
            Object.assign(data, submitP, ex);
            // 提交
            request.post({'path': config.saveInsurance}, data).then(function (res) {
                var ratingData = res.data;
                if (ratingData.ret != 0) {
                    that.setData({
                        disabled: false
                    });
                    return false;
                }
                if (ratingData.ret == 0) {
                    wx.navigateTo({
                        url: `/pages/work-center/work-center?type=3`
                    })
                    that.setData({
                        disabled: false
                    });
                }
            })
        }
    },
    inputKey: function (e) {
        let that = this;
        let lsData = that.data;
        let name = e.currentTarget.dataset.name;
        let nowatch = e.currentTarget.dataset.nowatch;

        let nameArr = name.split(".");
        let newVal = e.detail.value;
        let nameArrLen = nameArr.length
        for (let i = 0; i <= nameArrLen; i++) {
            let val = lsData[nameArr[i]];
            if (nameArrLen - 1 === i) {
                lsData[nameArr[i]] = newVal;
            } else {
                lsData = lsData[nameArr[i]];
            }
        }
        this.setData({
            submitP: that.data.submitP
        })


        if (!nowatch) {
            that.watchAutoChage(name)
        }


        // debugger
    },
    //监听数据变化响应
    watchAutoChage: function (name) {
        let that = this;
        let data = that.data;


        let submitP = data.submitP;
        // amount 实际收
        submitP.original_amount = hyMath.hyTofloat2(submitP.original_amount);  //商业险
        submitP.proportion = hyMath.hyTofloat2(submitP.proportion);     // 优惠比例
        submitP.amount = hyMath.hyTofloat2(submitP.amount);

        // 反查的逻辑---- 特殊设置
        if (name === 'submitP.amount') {
            if(submitP.amount > submitP.original_amount){
                submitP.amount = submitP.original_amount;
            }
            if(submitP.original_amount >0){
                let num1 = hyMath.hyjian(submitP.original_amount,submitP.amount);
                let num2 = hyMath.multiply(num1,100);
                let num3 = hyMath.accDiv(num2,submitP.original_amount);
                submitP.proportion =   hyMath.hyTofloat2(num3);
            }
            console.log(name, 'amount-------');
        } else {
            let pr = submitP.proportion / 100;
            submitP.amount = hyMath.hyjian(submitP.original_amount, hyMath.multiply(submitP.original_amount, pr));
            submitP.amount = submitP.amount > 0 ? submitP.amount : 0;
            submitP.amount = hyMath.hyTofloat2(submitP.amount);
        }


        this.setData({
            submitP: submitP
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let that = this;
        let urlP = that.data.urlP;
        let oldO = {};
        let newO = {};
        let items = urlP.items;
        let userInfo = that.data.userInfo;
        let submitEx = that.data.submitEx;
        if (typeof urlP.items != 'undefined') {
            oldO = {
                real_name: items.real_name,
                head_img_url: items.head_img_url,
                car: items.cars && items.cars[0] && items.cars[0].license_number,
                level: items.level
            }
            Object.assign(newO, userInfo, oldO)
            that.setData({
                userInfo: newO
            });

            // 修改扩展对象
            submitEx.member_id = items.member_id
            submitEx.old_member_id = items.old_member_id
            submitEx.car_plate = items.cars && items.cars[0] && items.cars[0].license_number

            if (items.cars == '') {
                wx.showToast({
                    title: '此用户没有车牌信息',
                    icon: 'success',
                    duration: 2000
                })
            }

            that.setData({
                submitEx: submitEx
            });
            that.setData({
                'urlP.items': undefined
            });
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})